package org.example.domain.activity.service.partake;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.domain.activity.model.aggregate.CreatePartakeOrderAggregate;
import org.example.domain.activity.model.entity.*;
import org.example.domain.activity.model.valobj.ActivityStateVO;
import org.example.domain.activity.repository.IActivityRepository;
import org.example.domain.activity.service.IActivityPartakeService;
import org.example.types.enums.ResponseCode;
import org.example.types.exception.AppException;

import java.util.Date;


/**
 * 用户参与活动抽奖抽象类
 * 模板设计模式应用
 * 用于定义方法总体流程,实现细节在子类中实现
 */
@Slf4j
public abstract class AbstractActivityPartake extends ActivityPartakeSupport implements IActivityPartakeService {


    public AbstractActivityPartake(IActivityRepository activityRepository) {
        super(activityRepository);
    }

    /**
     * 创建抽奖订单,扣减活动库存
     * @param partakeRaffleActivityEntity 参与抽奖活动实体对象:用户id,活动id
     * @return
     */
    @Override
    public UserRaffleOrderEntity createOrder(PartakeRaffleActivityEntity partakeRaffleActivityEntity) {
        //1.参数校验
        Long activityId = partakeRaffleActivityEntity.getActivityId();
        String userId= partakeRaffleActivityEntity.getUserId();
        if (StringUtils.isBlank(userId) || activityId == null){
            throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(),ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }

        //2.规则校验
        ActivityEntity activityEntity = activityRepository.queryActivityEntityByActivityId(activityId);
        checkActivityState(activityEntity);

        // 3. 查询未被使用的活动参与订单记录,有直接返回,没有则创建抽奖订单,但是创建了不等于抽奖了,因为还未被消费,所以这里创建的订单都是create状态的
        UserRaffleOrderEntity userRaffleOrderEntity = activityRepository.queryNoUsedRaffleOrder(partakeRaffleActivityEntity);
        if (null != userRaffleOrderEntity) {
            log.info("创建参与活动订单 userId:{} activityId:{} userRaffleOrderEntity:{}", userId, activityId, JSON.toJSONString(userRaffleOrderEntity));
            return userRaffleOrderEntity;
        }

        //检查日额度和月额度是否存在,不存在则同步总账户数据
        checkMonthDayIsExist(userId,activityId,currentDate);

        //4.构建抽奖订单对象
        userRaffleOrderEntity = buildUserRaffleOrderEntity(userId,activityEntity);

        //5.生成的订单写入数据库并账户扣减
        activityRepository.saveUserRaffleOrderEntity(userRaffleOrderEntity,currentDate);

        //6.生成用户抽奖订单,并写入数据库
        return userRaffleOrderEntity;
    }


    /**
     * 创建用户参与活动抽奖订单
     * @param userId 用户id
     * @param activityEntity 活动实体
     * @return
     */
    protected abstract UserRaffleOrderEntity buildUserRaffleOrderEntity(String userId, ActivityEntity activityEntity);

}
